package com.common;

import com.common.retrofit.RxObserver;
import com.util_code.base.mvp.MvpView;
import com.util_code.utils.RxUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

public class CountDownUtlis {

    private MvpView mvpView;

    public CountDownUtlis(MvpView mvpView) {
        this.mvpView = mvpView;
    }

    /**
     *
     * @param watingTime 倒计时S
     * @param countDownListener 计时监听
     */
    public void countDown(int watingTime, CountDownListener countDownListener) {
        countDownListener.onCountStart();
        Observable.interval(0, 1, TimeUnit.SECONDS)
                /*.takeUntil(new Predicate<Long>() {
                    @Override
                    public boolean test(Long aLong) throws Exception {
                        // 包含临界条件,条件满足则结束
                        return aLong >= Constant.VALIDETE_CODE_WATING_TIME_MAX;
                    }
                })*/
                .takeWhile(new Predicate<Long>() {
                    @Override
                    public boolean test(Long aLong) throws Exception {
                        // 不包含临界条件,条件不满足则结束
                        return aLong <= watingTime;
                    }
                })
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtils.<Long>applySchedulersLifeCycle(mvpView))
                .subscribe(new RxObserver<Long>() {

                    @Override
                    public void onNext(Long aLong) {
//                        LogUtil.i("onNext = " + aLong);
                        long diff = watingTime - aLong;
                        countDownListener.onCountProgress(diff);
                        //倒计时完毕后，按钮可以再次被点击，重新设置按钮文案
                        if (diff == 0) {
                            countDownListener.onCountEnd();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        countDownListener.onCountError();
                    }
                });
    }

    public interface CountDownListener {

        void onCountStart();

        void onCountProgress(long progress);

        void onCountEnd();

        void onCountError();

    }

}
